import { ElMessage } from '@/stores/elMessage'
import { i18n, initWebSocket } from '@/utils'
import { ref, type Ref } from 'vue'
export const musicMessage: Ref<Record<string, any>> = ref({})
export const musicList: any = ref([])
export const deleteMusicList: any = ref([])
export const birStatus = ref('')
export const lightStatus = ref('')
// 标记是否已经连接 websocket
export const isOpenFeedback = ref(false)
let ws: WebSocket | undefined

//断开重连定时器
let reconnectInterval: number | NodeJS.Timeout | null = null

// 关闭 websocket
export const tryCloseWS = () => {
  if (ws instanceof WebSocket) {
    ws?.close()
    ws = undefined
  }
  clearReconnectInterval()
}

// 关闭页面前先关闭 websocket
// onBeforeUnmount(tryCloseWS)

// 清除重连定时器
const clearReconnectInterval = () => {
  if (reconnectInterval) {
    clearInterval(reconnectInterval)
    reconnectInterval = null
  }
}

// 连接 WebSocket
export const connectWebSocket = () => {
  ws = initWebSocket('/websocket/patroling/feedback', {
    onmessage: (event: MessageEvent<any>) => {
      const data = JSON.parse(event.data)
      if (data.type === 4) {
        if (data.code === 'ADAS') {
          musicMessage.value = data.message
          filterMusic()
        } else if (data.code === 'ADAG') {
          musicList.value = data.message
          filterMusic()
        } else {
          musicMessage.value = {
            volumeValue: '',
            index: '',
            mode: '',
            name: '',
            status: ''
          }
          musicList.value.length = 0
          deleteMusicList.value.length = 0
        }
      } else if (data.type === 6) {
        birStatus.value = data.message
      } else if (data.type === 7) {
        lightStatus.value = data.message
      }
    },

    onopen: () => {
      isOpenFeedback.value = true
      ElMessage({
        type: 'success',
        message: i18n.global.t('jian-ting-shang-zhuang-kong-zhi-lian-jie-cheng-gong')
      })
      clearReconnectInterval()
    },
    onclose: () => {
      isOpenFeedback.value = false
      ElMessage({
        type: 'warning',
        message: i18n.global.t('jian-ting-shang-zhuang-kong-zhi-lian-jie-duan-kai')
      })
      // 断开后每隔一段时间重新连接
      startReconnectInterval()
    },
    onerror: () => {
      isOpenFeedback.value = false
      ElMessage({
        type: 'warning',
        message: i18n.global.t('jian-ting-shang-zhuang-kong-zhi-lian-jie-cuo-wu')
      })
      // 出错后每隔一段时间重新连接
      startReconnectInterval()
    }
  })
}

// 过滤正在播放的音乐
function filterMusic() {
  if (typeof musicMessage.value.index === 'string' && musicMessage.value.index !== '') {
    const indexToDelete = parseInt(musicMessage.value.index)
    if (musicList.value.length !== 0) {
      deleteMusicList.value = musicList.value.filter(
        (_: any, currentIndex: any) => currentIndex !== indexToDelete
      )
    }
  }
}

// 开始重连定时器
export const startReconnectInterval = () => {
  if (!reconnectInterval) {
    reconnectInterval = setInterval(() => {
      tryCloseWS()
      ElMessage({
        type: 'warning',
        message: i18n.global.t('websocket-duan-kai-zhong-lian-zhong')
      })
      connectWebSocket()
    }, 5000) // 每隔5秒重新连接
  }
}
